package com.yhx.security.config;

import com.yhx.iservice.IPermissionService;
import com.yhx.iservice.IRoleService;
import com.yhx.iservice.IUserService;
import com.yhx.pojo.Permission;
import com.yhx.pojo.Role;
import com.yhx.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Reference
    private IUserService iUserService;
    @Reference
    private IRoleService iRoleService;
    @Reference
    private IPermissionService iPermissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = iUserService.getByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户名不正确！！！");
        }
        List<Role> roles = iRoleService.roleListByUserId(user.getId());
        ArrayList<SimpleGrantedAuthority> list = new ArrayList<>();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
        }

        List<Permission> permissions = iPermissionService.listByUserId(user.getId());
        for (Permission permission : permissions) {
            list.add(new SimpleGrantedAuthority(permission.getKeyword()));
        }
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
    }
}
